import time
from pathlib import Path
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from FileRenamer import FileRenamer
from PersistentChromeDriver import PersistentChromeDriver

chrome = PersistentChromeDriver(profile_name="my_profile")
driver = chrome.start_browser()
download_dir = r"D:\kuang\Downloads"
renamer = FileRenamer(download_dir)
wait = WebDriverWait(driver, 30)
start_page = 2


def get_folder_file_count(folder_path):
    """
    获取文件夹中的文件数量
    :param folder_path: 文件夹路径(str 或 Path对象)
    :return: 文件数量(int)
    """
    folder_path = Path(folder_path)
    try:
        # 获取文件夹中的所有文件(不包括文件夹)
        files = [f for f in folder_path.iterdir() if f.is_file()]
        # 排除临时下载文件
        complete_files = [f for f in files if not f.name.endswith('.crdownload') and not f.name.endswith('.tmp')]
        return len(complete_files)
    except Exception as e:
        print(f"获取文件数量时出错: {str(e)}")
        return 0


def wait_for_file_count_change(folder_path, initial_count, timeout=30, check_interval=0.5):
    """
    等待文件夹中的文件数量发生变化
    :param folder_path: 文件夹路径
    :param initial_count: 初始文件数量
    :param timeout: 超时时间(秒)
    :param check_interval: 检查间隔(秒)
    :return: 成功返回True，超时返回False
    """
    start_time = time.time()
    while time.time() - start_time < timeout:
        current_count = get_folder_file_count(folder_path)
        if current_count > initial_count:
            # 等待文件完全写入
            time.sleep(1)
            return True
        time.sleep(check_interval)
    return False


def get_content():
    ppt_list = wait.until(
        EC.presence_of_element_located((By.XPATH, "/html/body/div[2]/div/div/div[1]/div[6]/div[2]/div[2]")))

    child_list = ppt_list.find_elements(By.XPATH, "./div")
    print(len(child_list))
    for i in child_list:
        initial_count = get_folder_file_count(download_dir)
        print(f"初始文件数量: {initial_count}")
        driver.execute_script("arguments[0].scrollIntoView();", i)
        label = i.find_element(By.XPATH, ".//div/a/div[2]/span[1]")
        download = i.find_element(By.XPATH, ".//div/a/div[1]/div[2]/button[2]")
        download.click()
        time.sleep(5)
        # 等待文件数量变化
        if wait_for_file_count_change(download_dir, initial_count):
            print("检测到新文件下载完成")
            current_count = get_folder_file_count(download_dir)
            print(f"当前文件数量: {current_count}")
            renamer.rename_latest_file(label.text)
            print("==========================================")
        else:
            print("下载超时或失败")


# 访问网站
driver.get(
    "https://www.officeplus.cn/WORD/?currentSubCat=00000000-0000-0000-0000-000000000000&popularity=Total&industry=&purpose=&paymentMethod=1&keywords=")

# 这里加入等待用户输入，防止闪退
for i in range(0, 100):
    time.sleep(2)
    if i >= start_page:
        get_content()
    try:
        next_page = wait.until(
            EC.presence_of_element_located(
                (By.XPATH, "/html/body/div[2]/div/div/div[1]/div[6]/div[2]/div[3]/div/span[last()]")))
        driver.execute_script("arguments[0].scrollIntoView();", next_page)

    except Exception:
        print("通过ID未能找到下一页按钮元素")

    next_page.click()

driver.quit()  # 程序结束推出webDriver
